<script lang="ts" setup>
import dayjs, { Dayjs } from 'dayjs';
import type { SelectProps } from 'ant-design-vue';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import { Button, Card, message, Step, Steps, Tabs, TabPane } from 'ant-design-vue';
import { ref, watch, computed } from 'vue';
import { MdiDelete } from '@vben/icons';
import { Page, useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getChemicalInfoApi, handleMSDSdataApi } from '#/api';
import { confirmModal } from '#/components';

import {
  commonFormConfig,
  FirstFormSchemas,
  SecondFormSchemas1,
  SecondFormSchemas2,
  SecondFormSchemas3,
  SecondFormSchemas4,
  SecondFormSchemas5,
  SecondFormSchemas6,
  SecondFormSchemas7,
  SecondFormSchemas8,
  SecondFormSchemas9,
  SecondFormSchemas10,
  SecondFormSchemas11,
  SecondFormSchemas12,
  SecondFormSchemas13,
  SecondFormSchemas14,
  SecondFormSchemas15,
  SecondFormSchemas16,
  compInfoTableSchemas,
} from './schemas';

// MSDS的十六部分
const MSDSpanes = ref<{ title: string; content: string; key: string }[]>([
  { title: '化学品及企业标识', key: '0' },
  { title: '危险性概述', key: '1' },
  { title: '成分/组成信息', key: '2' },
  { title: '急救措施', key: '3' },
  { title: '消防措施', key: '4' },
  { title: '泄漏应急处理', key: '5' },
  { title: '操作处置与储存', key: '6' },
  { title: '接触控制/个体防护', key: '7' },
  { title: '理化特性', key: '8' },
  { title: '稳定性和反应性', key: '9' },
  { title: '毒理学资料', key: '10' },
  { title: '生态学资料', key: '11' },
  { title: '废弃处置', key: '12' },
  { title: '运输信息', key: '13' },
  { title: '法规信息', key: '14' },
  { title: '其它信息', key: '15' },
]);
// 默认值
const originalData = {
  msdsNo: 'WOSHIJIADE',
  component: '[]',
  isSubstance: '',
  chemNameCn: '',
  chemNameEn: '',
  companyName: '四川润泰特种气体有限公司',
  companyAddr: '广汉市连山镇柳埝村七组',
  postalCode: '618300',
  contactEmail: 'cs@wintecgas.com',
  faxNum: '0838-6833368',
  emerPhone: '0838-6833368',
  natEmerPhone: '公安报警110、火警电话119、医院急救电话120',
  productUse: '用于校准气体分析仪器，评价和检验分析方法，仲裁分析结果，保证测量结果的溯源性和可靠性。',
  emerSummary: '压缩气体，遇热可能爆炸。如果吸入，请将患者移到新鲜空气处。',
  ghsHazClass: '[]',
  pictogram: '["GHS04高压气体"]',
  warningWord: '危险',
  hazardDesc: '内装高压气体，遇热可能爆炸。',
  prevMeasure: '避免与氧化剂、强碱、强酸、金属及有机溶剂混合使用。\n避免阳光直射。',
  accResponse: '如果吸入，请将患者移到新鲜空气处。',
  safeStorage: '储存在阴凉通风处，保持容器密闭。',
  disposalMethod: '本品及内装物、容器依据国家和地方法规处置。',
  physChemHaz: '内装高压气体，遇热可能爆炸。',
  healthHazard: '吸入有害气体，可能引起头晕、头痛、恶心、呕吐、皮肤刺激等。',
  envHazard: '可能对环境造成污染。',
  inhaleAid: '迅速转移至空气新鲜处，若无呼吸，立即进行人工呼吸。若呼吸困难，输氧，就医。',
  skinAid: '若有冻伤，用温水复温，立即就医。',
  eyeAid: '谨慎起见，用水冲洗眼睛。',
  rescuerAdv: '根据需要使用个人防护用品。',
  doctorNote: '对症处理。',
  extAgent: '雾状水、泡沫、二氧化碳、干粉。',
  specHazard: '若与高热，容器内压增大，有开裂和爆炸的危险。',
  firePrecaution: '将危险区域的人员疏散，从远处向钢瓶喷水降温，在无危险的情况下，将钢瓶移出火灾区域并止住泄漏。',
  leakProtect:
    '根据气体扩散的影响区域划定警戒区，无关人员从侧风、上风向撤离至安全区。建议应急处理人员戴正压自给式呼吸器，穿防静电工作服。尽可能切断泄漏源。',
  envProtect: '如能确保安全，可采取措施防止进一步的泄漏。',
  leakCleanup:
    '保护气瓶下于良好通风或户外，然后缓慢将废气直接排入大气。请注意当地废弃处置法规，将该物质及其容器送回本公司处置。',
  handleNote:
    '使用合适的工具搬运钢瓶，切忌野蛮操作。严禁使用钢瓶帽吊装。严禁插入物件（如拍扳手、起子、撬杠等）来开启瓶帽，这样会危害阀门，导致泄漏。用可调皮带拍扳手开启过紧或锈蚀瓶帽。缓慢开启阀门，如果阀门难以打开，不要使用并联系供应商。每次用完后关闭阀门。当气瓶空后保持关闭。密闭操作，加强通风。操作员必须经过专门培训，严格遵守操作规程，必要时佩戴自给式呼吸器，遵守规章制度，遵守劳动纪律。',
  storageNote:
    '应存放于通风良好，远离火种、热源，温度不高于50℃的地方。存放时，钢瓶应处于直立状态，用防倾倒链条固定，装好阀门保护罩。空、满瓶分开储存。以先进先出的原则，保证满瓶勿长时间存放。',
  occLimitCn: '无资料。',
  occLimitUs: '无资料。',
  bioLimit: '无资料。',
  airTestMtd: '无资料。',
  bioTestMtd: '无资料。',
  engControl: '密闭操作。提供良好的自然通风条件。',
  respProtect: '一般不需特殊防护。当作业场所空气中氧气浓度低于18%时，必须佩戴空气呼吸器或长管面具。',
  eyeProtect: '一般不需特殊防护。',
  skinProtect: '穿一般作业工作服。',
  handProtect: '佩戴一般作业防护手套。',
  stability: '在建议的储存条件下是稳定的。',
  hazardReact: '无资料。',
  avoidCond: '无资料。',
  incompat: '无资料。',
  decompProd: '无资料。',
  acuteToxic: '无资料。',
  skinIrrit: '无资料。',
  eyeIrrit: '无资料。',
  respAllergy: '无资料。',
  germMut: '无资料。',
  carcinogen: '无资料。',
  reprodToxic: '无资料。',
  targOrg1: '无资料。',
  targOrgRep: '无资料。',
  inhaleHaz: '无资料。',
  ecoToxic: '无资料。',
  biodeg: '无资料。',
  abioDeg: '无资料。',
  bioaccum: '无资料。',
  soilMobility: '无资料。',
  chemDispose:
    '不要尝试处理残留和剩余物，请送回本公司处理。紧急情况下，保护气瓶处于良好通风或户外，然后缓慢将废气直接排入大气。',
  contamPkg: '将容器送回本公司或按国家和地方法规处置。',
  dispNote: '处置前应参阅国家和地方法规。',
  unNumber: '无资料。',
  transName: '无资料。',
  transHazCls: '无资料。',
  pkgClass: '无资料。',
  pkgMark: '["GHS04高压气体"]',
  marinePoll: '无资料。',
  transNote: '无资料。',
  occDiseaseCat: '未列入。',
  hazChemList: '未列入。',
  expChemList: '未列入。',
  imhazChemList: '未列入。',
  majorHazard: '未列入。',
  highToxList: '未列入。',
  ctrlChemList: '未列入。',
  stkhlmConv: '未列入。',
  rotterConv: '未列入。',
  mtlProtocol: '未列入。',
  revNote: '本SDS按照《化学品安全技术说明书编写指南》(GBT17519 - 2013)标准制。',
  otherHdlStorHaz:
    '高压气体，使用的管道和设备需经设计能够承受相应的压力和温度。在管道中使用防逆流装置。气体可以导致缺氧快速窒息。在充足的通风条件下储存和使用。禁止将气瓶放置在可能产生电气回路的地方。',
  fillDept: 'WTC生技部',
  refDocs: 'WTCSDS、《危险化学品安全技术大典》等。',
  otherInfo:
    '根据MSDS及商标上的说明向供应商索取免费的四川润泰特种气体有限公司安全文献，四川润泰特种气体有限公司要求本产品的使用者详细阅读产品的SDS，并了解产品的危险性和安全信息。为提高使用本产品的安全性，使用者应做到：①告知其顾员、代理商和承包商SDS上的信息和其他任何已知的产品的危害性和安全信息；②向本产品的购买者提供相关的SDS的资料；③要求本产品的购买者向他的雇员、客户提供产品危害性和安全信息。',
};

// 定义一个接口 compInfoTabRowType，用于描述表格行数据的结构（组分、浓度、CAS号、类别）
interface compInfoTabRowType {
  compName: string;
  compConc: number;
  casNo: string;
  hazCat: string;
}
interface chemPropsTabRowType {
  chemName: string; // 化学物质名称
  appearance: string; // 外观与性状
  phValue: string; // pH值
  meltPoint: string; // 熔点(℃)
  boilPoint: string; // 沸点(℃)
  relDensity: string; // 相对密度(水=1)
  vaporDens: string; // 相对蒸气密度(空气=1)
  vaporPress: string; // 饱和蒸气压(kPa)
  critPress: string; // 临界压力(MPa)
  octanolCoef: string; // 辛醇/水分配系数
  flashPoint: string; // 闪点(℃)
  igniteTemp: string; // 自燃温度(℃)
  explLower: string; // 爆炸下限[%(V/V)]
  explUpper: string; // 爆炸上限[%(V/V)]
  decompTemp: string; // 分解温度(℃)
  viscosity: string; // 黏度（mPa.s）
  combustHeat: string; // 燃烧热(kJ/mol)
  critTemp: string; // 临界温度(℃)
  solubility: string; // 溶解性
}
let componentOptions = ref<SelectProps['options']>([]);
// 定义一个RowType类型空数组，用于存放组分数据
let compInfoGrid_data: compInfoTabRowType[] = [];

const needMerge = ref(true);
let currentCard = ref(0); // 记录当前是第几个步骤条
let activeTab = ref(MSDSpanes.value[0].key); // 记录当前是哪个panes
let currentTab = ref(0); // 记录当前是第二个卡片的第几个表单
let isCollapsed = ref(false); // 记录当前是否折叠
let isGridLoaded = false; // 记录表格是否加载完成

const record = ref(); // 记录调用modal时传递过来的数据
const isUpdate = ref(false); // 记录当前是否是更新状态
const saveas = ref(false); // 记录当前是否是需要另存为
const gridApi = ref(); // 记录调用时传递过来表格实例
let originComponent: any[] = []; // 记录原始的组分数据

/* 第一个Card的表单 */
const [FirstForm, firstFormApi] = useVbenForm({
  ...FirstFormSchemas,
  ...commonFormConfig,
  showCollapseButton: true,
  collapsed: false,
  collapsedRows: 0,
  handleSubmit: onFirstSubmit,
  resetButtonOptions: {
    show: false,
  },
  submitButtonOptions: {
    // 按钮显示文本
    content: '下一步',
  },
});

/* 第二个Card的表单 */
const compInfoOptions: VxeGridProps<compInfoTabRowType> = {
  ...compInfoTableSchemas,
  border: true,
  autoResize: true,
  keepSource: true, // 是否保留源数据，用于重置表格
  maxHeight: 450,
  showOverflow: false,
};
const compInfogridEvents: VxeGridListeners<compInfoTabRowType> = {
  editClosed: ({ row }) => {
    const sumResult = sumConcentration();
    if (!sumResult) {
      row.compConc = null;
    }
  },
};
const [compInfoGrid, compInfoGridApi] = useVbenVxeGrid({
  gridOptions: compInfoOptions, // 保持属性名为 gridOptions
  gridEvents: compInfogridEvents, // 传递事件配置
});

// SecondForm1到SecondForm16
const [SecondForm1, second1FormApi] = useVbenForm({
  ...SecondFormSchemas1,
  ...commonFormConfig,
  handleReset: onSecondReset,
  handleSubmit: nextBtn,
  resetButtonOptions: {
    content: '上一步',
  },
  wrapperClass: 'grid-cols-2',
});
const [SecondForm2, second2FormApi] = useVbenForm({
  ...SecondFormSchemas2,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
});
const [SecondForm3, second3FormApi] = useVbenForm({
  ...SecondFormSchemas3,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
});
const [SecondForm4, second4FormApi] = useVbenForm({
  ...SecondFormSchemas4,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
});
const [SecondForm5, second5FormApi] = useVbenForm({
  ...SecondFormSchemas5,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
});
const [SecondForm6, second6FormApi] = useVbenForm({
  ...SecondFormSchemas6,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
});
const [SecondForm7, second7FormApi] = useVbenForm({
  ...SecondFormSchemas7,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
});
const [SecondForm8, second8FormApi] = useVbenForm({
  ...SecondFormSchemas8,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
  wrapperClass: 'grid-cols-2',
});
const [SecondForm9, second9FormApi] = useVbenForm({
  ...SecondFormSchemas9,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
  wrapperClass: 'grid-cols-3',
});
const [SecondForm10, second10FormApi] = useVbenForm({
  ...SecondFormSchemas10,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
  wrapperClass: 'grid-cols-2',
});
const [SecondForm11, second11FormApi] = useVbenForm({
  ...SecondFormSchemas11,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
  wrapperClass: 'grid-cols-2',
});
const [SecondForm12, second12FormApi] = useVbenForm({
  ...SecondFormSchemas12,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
  wrapperClass: 'grid-cols-2',
});
const [SecondForm13, second13FormApi] = useVbenForm({
  ...SecondFormSchemas13,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
});
const [SecondForm14, second14FormApi] = useVbenForm({
  ...SecondFormSchemas14,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: nextBtn,
  wrapperClass: 'grid-cols-2',
});
const [SecondForm15, second15FormApi] = useVbenForm({
  ...SecondFormSchemas15,
  ...commonFormConfig,
  labelWidth: 200,
  handleReset: preBtn,
  handleSubmit: nextBtn,
  wrapperClass: 'grid-cols-3',
});
const [SecondForm16, second16FormApi] = useVbenForm({
  ...SecondFormSchemas16,
  ...commonFormConfig,
  handleReset: preBtn,
  handleSubmit: onSecondSubmit,
  submitButtonOptions: {
    // 按钮显示文本
    content: '提交',
  },
  wrapperClass: 'grid-cols-2',
});

const formApis = [
  second1FormApi,
  second2FormApi,
  second3FormApi,
  second4FormApi,
  second5FormApi,
  second6FormApi,
  second7FormApi,
  second8FormApi,
  second9FormApi,
  second10FormApi,
  second11FormApi,
  second12FormApi,
  second13FormApi,
  second14FormApi,
  second15FormApi,
  second16FormApi,
];

/* 通过弹窗方式加载当前内容 */
const [VbenModal, modalApi] = useVbenModal({
  // 默认全屏
  fullscreen: true,
  confirmText: '提交',
  draggable: true,
  closeOnPressEscape: false,
  closeOnClickModal: false,

  onOpenChange(isOpen) {
    isUpdate.value = modalApi.getData()?.isUpdate ?? false;
    saveas.value = modalApi.getData()?.saveas ?? false;
    record.value = isOpen ? modalApi.getData()?.record || {} : {};
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen && isUpdate.value) {
      processData(record.value?.msdsNo).then((res) => {
        if (res === 'err') {
          console.log('弹窗前处理数据出错');
        }
      });
    } else if (isOpen && !isUpdate.value) {
      processData(originalData.msdsNo).then((res) => {
        if (res === 'err') {
          console.log('弹窗前处理数据出错');
        }
      });
    }
  },
  onConfirm() {
    return onSecondSubmit();
  },
  onClosed() {
    // 关闭时重置表单及变量
    formApis.forEach((formApi) => {
      formApi.resetForm();
    });
    compInfoGrid_data.splice(0, compInfoGrid_data.length);
    compInfoGridApi.grid.reloadData(compInfoGrid_data);
    originComponent.splice(0, originComponent.length);
    currentTab.value = 0;
    currentCard.value = 0;
    activeTab.value = MSDSpanes.value[0].key;
    isCollapsed.value = false;
    isGridLoaded = false;
  },
});

/*==============================函数过程===============================*/
// 数据处理函数
async function processData(msdsNo: any) {
  const fields = ['compInfoTable', 'component', 'ghsHazClass', 'pictogram', 'pkgMark'];
  let data;
  if (msdsNo === 'WOSHIJIADE') {
    data = originalData;
    data.fillDate = dayjs();
  } else {
    const res = await handleMSDSdataApi('getInfo', msdsNo);
    data = res[0];
    data.fillDate = <Dayjs>dayjs(data.fillDate);
  }

  fields.forEach((item) => {
    if (data[item] && typeof data[item] === 'string') {
      try {
        data[item] = JSON.parse(data[item]);
      } catch (error) {
        console.log(`处理字段 ${item} 时出错:`, error);
        return 'err';
      }
    }
  });

  originComponent.push(...data.component);

  // 表单赋值
  try {
    firstFormApi.setValues(data);
    formApis.forEach((formApi) => {
      formApi.setValues(data);
    });

    // 表格赋值
    if (msdsNo !== 'WOSHIJIADE') {
      compInfoGrid_data.splice(0, compInfoGrid_data.length);
      data.compInfoTable.forEach((item: any) => {
        compInfoGrid_data.push({
          compName: item.compName,
          compConc: item.compConc,
          casNo: item.casNo,
          hazCat: item.hazCat,
        });
      });
      compInfoGridApi.grid.reloadData(compInfoGrid_data);
    }
    return 'ok';
  } catch (error) {
    console.error(`赋值时出错:`, error);
    return 'err';
  }
}

// 比较函数
function compareComponents(proxyObj, array) {
  const proxyValues = Object.values(proxyObj);
  if (proxyValues.length !== array.length) {
    return false;
  }
  const sortedProxy = proxyValues.slice().sort();
  const sortedArray = array.slice().sort();
  for (let i = 0; i < sortedProxy.length; i++) {
    if (sortedProxy[i] !== sortedArray[i]) {
      return false;
    }
  }
  return true;
}

/*--------------------------表单函数-----------------------------*/
const handleAdd = async () => {
  // 待完善
  const record = {};
  const { row: newRow } = await compInfoGridApi.grid.insertAt(record, -1);
  compInfoGridApi.grid.setEditRow(newRow);
};
const handleRemove = async (row: compInfoTabRowType) => {
  compInfoGridApi.grid.remove(row);
};
const handleRemoveSelected = async () => {
  const selectedRows = await compInfoGridApi.grid.getCheckboxRecords();
  if (selectedRows.length > 0) {
    compInfoGridApi.grid.removeCheckboxRow();
    message.success('删除成功');
  } else {
    message.info('请至少选择一行数据');
  }
};

const handleReload = async () => {
  compInfoGridApi.grid.reloadData(compInfoGrid_data);
};

const sumConcentration = async () => {
  const { fullData } = compInfoGridApi.grid.getTableData();
  const sum = fullData.reduce((acc: number, row: compInfoTabRowType) => acc + (Number(row.compConc) || 0), 0);
  // 浓度不能小于0，也不能大于100
  const sumValid = sum > 0 && sum <= 100;
  return sumValid;
};

/*==============================表单事件===============================*/
async function ValidGrid(GridIndex: number) {
  // 获取表格行数
  const rowCount = compInfoGridApi.grid.getTableData().fullData.length;
  if (rowCount === 0) {
    return false;
  }
  if (GridIndex === 2) {
    const sumResult = await sumConcentration();
    if (!sumResult) {
      return '浓度总和不正确!';
    }
  }
  const errMap = await compInfoGridApi.grid.fullValidate(true);
  // 验证结果：验证通过返回undefined（!errMap=true)，验证不通过返回一个对象(!errMap=false);
  if (!!errMap) {
    return '表格信息不完整！';
  }
  return !errMap;
}

const validateForm = async (formApi, needSubmit: boolean = false) => {
  const result = needSubmit ? await formApi.validateAndSubmitForm() : await formApi.validate();
  // 如果 needSubmit 为 true，result !== undefined表示表单提交成功
  // 如果 needSubmit 为 false，则返回表单验证结果result.valid
  return needSubmit ? result !== undefined : result.valid;
};

// 第二个Card的表单验证函数
async function validateSecondForms(start = 0, end = formApis.length) {
  for (let i = start; i < end; i++) {
    const isValid = [2].includes(i) ? await ValidGrid(i) : await validateForm(formApis[i]);
    if (isValid !== true) {
      currentCard.value = 1;
      activeTab.value = MSDSpanes.value[i].key;
      currentTab.value = i;
      return isValid;
    }
  }
  return true;
}

async function onFirstSubmit(values: Record<string, any>) {
  // 调用比较函数，比较组分是否发生了变化(用于编辑等操作时保留浓度数据)
  const isSame = compareComponents(values.component, originComponent);

  if (!isSame) {
    // 清空componentOptions、compInfoGrid_data数组
    componentOptions.value = [];
    compInfoGrid_data.splice(0, compInfoGrid_data.length);

    // 将values.component中的每个元素添加到componentOptions数组中
    componentOptions.value = values.component.map((item: string) => ({
      label: item,
      value: item,
    }));

    // 使用API接口获取CAS号
    const result = await getChemicalInfoApi(JSON.stringify(componentOptions.value));
    // 初始化表格数据compInfoGrid_data
    result.forEach((item: any) => {
      compInfoGrid_data.push({
        compName: item.name,
        compConc: null,
        casNo: item.casNo,
        hazCat: item.hazCat,
      });
    });
    // 推荐在此处完成表格数据初始化
    // 也可放在步骤切换事件内；因直接点击步骤条时表格数据并未加载完成，导致验证表格时误通过的BUG已修复
    if (!isGridLoaded) {
      compInfoGridApi.grid.loadData(compInfoGrid_data);
      isGridLoaded = true;
    }
  }
  currentCard.value = 1;
}

function onSecondReset() {
  currentCard.value = 0;
}
async function onSecondSubmit() {
  // 二次确认
  const confirmRes = await confirmModal('提交确认', '即将提交数据，是否继续？');
  if (!confirmRes) return;

  // 锁定modal
  modalApi.setState({ loading: true, confirmLoading: true });
  message.loading({
    content: '数据验证处理中，请稍后...',
    duration: 0,
    key: 'beforeSubmit',
  });
  // 延迟0.5秒，确保全局loading生效，防止用户再次操作
  await new Promise((resolve) => setTimeout(resolve, 500));

  // 验证第二个卡片的所有表单
  const isValid = await validateSecondForms();
  if (isValid !== true) {
    modalApi.setState({ loading: false, confirmLoading: false });
    message.error({ content: isValid, key: 'beforeSubmit' });
    return;
  }

  const values = await firstFormApi
    .merge(second1FormApi)
    .merge(second2FormApi)
    .merge(second3FormApi)
    .merge(second4FormApi)
    .merge(second5FormApi)
    .merge(second6FormApi)
    .merge(second7FormApi)
    .merge(second8FormApi)
    .merge(second9FormApi)
    .merge(second10FormApi)
    .merge(second11FormApi)
    .merge(second12FormApi)
    .merge(second13FormApi)
    .merge(second14FormApi)
    .merge(second15FormApi)
    .merge(second16FormApi)
    .submitAllForm(needMerge.value);
  // 增加表格数据
  const compInfoData = compInfoGridApi.grid.getTableData().fullData;
  values.compInfoTable = compInfoData;
  // 格式化时间，避免时间格式不一致导致的问题
  values.fillDate = dayjs(values.fillDate).format('YYYY-MM-DD HH:mm:ss');
  values.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 更新时间

  // 提交到后端, 处理MSDS编号
  let msdsNo;
  if (isUpdate.value && !saveas.value) {
    // 此时为编辑
    msdsNo = record.value?.msdsNo;
  } else {
    // 先获取MSDS编号
    const msdsNoMax = await handleMSDSdataApi('getInfo', null, 'max');
    msdsNoMax === '0'
      ? (msdsNo = 'WTC-0001')
      : (msdsNo = 'WTC-' + (parseInt(msdsNoMax.split('-')[1]) + 1).toString().padStart(4, '0'));
  }

  // 提交数据
  handleMSDSdataApi('submit', msdsNo, JSON.stringify(values))
    .then(() => {
      message.success({ content: '提交成功', key: 'beforeSubmit' });
      gridApi.value?.reload();
      modalApi.close();
    })
    .catch((err) => {
      modalApi.setState({ loading: false, confirmLoading: false });
      message.error({
        content: `提交失败：${err.message}`,
        key: 'beforeSubmit',
      });
    })
    .finally(() => {
      modalApi.setState({ loading: false, confirmLoading: false });
    });
}

/*==============================步骤条、卡片、Tab切换过程===============================*/
/* 为保证切换的流畅性，将验证过程放到最后一个表单提交时 */
// 点击步骤条切换事件
async function onChange(current) {
  if (current < currentCard.value) {
    currentCard.value = current;
    return;
  }

  let isValid = true;
  // 第一个卡片切换时必须进行验证并提交，保证选择的组分信息能够传递到第二个卡片
  if (currentCard.value === 0) {
    isValid = await validateForm(firstFormApi, true);
  }

  isValid ? (currentCard.value = current) : message.error('请先完成信息填写！');
}
// 展开/折叠切换
async function toggleCollapse() {
  isCollapsed.value = !isCollapsed.value;
  // 如果是第二个卡片，则切换时需要根据currentTab的值进行切换
  if (currentCard.value === 0) {
    firstFormApi.setState({ collapsed: isCollapsed.value });
  } else if (currentCard.value === 1) {
    formApis[currentTab.value].setState({ collapsed: isCollapsed.value });
  }
}

// 第二个Card的Tab标签页切换事件
async function preBtn() {
  const currentIndex = MSDSpanes.value.findIndex((pane) => pane.key === activeTab.value);
  if (currentIndex > 0) {
    activeTab.value = MSDSpanes.value[currentIndex - 1].key;
  } else if (currentIndex === 0) {
    currentCard.value = 0;
  }
}
async function nextBtn() {
  const currentIndex = MSDSpanes.value.findIndex((pane) => pane.key === activeTab.value);

  if (currentIndex < MSDSpanes.value.length - 1) {
    activeTab.value = MSDSpanes.value[currentIndex + 1].key;
  } else if (currentIndex === MSDSpanes.value.length - 1) {
    await onSecondSubmit();
  }
}

/*==============================监听事件===============================*/
// 监听是否发生Card切换，如果发生切换则及时更新isCollapsed的值为当前formApi的collapsed值
watch(currentCard, (newVal) => {
  if (newVal === 0) {
    isCollapsed.value = firstFormApi.getState().collapsed;
  } else if (newVal === 1) {
    isCollapsed.value = formApis[currentTab.value].getState().collapsed;
  }
});
// 监听第二个Card的Tab是否发生切换，如果发生切换则及时更新currentTab的值用于决定显示哪个表单
watch(activeTab, async (newVal) => {
  const index = MSDSpanes.value.findIndex((pane) => pane.key === newVal);

  currentTab.value = index;
  isCollapsed.value = formApis[index].getState().collapsed; // 更新isCollapsed的值
});

/*==============================其他事件===============================*/
const maxWidthClass = computed(() => {
  return currentTab.value === 2 ? 'max-w-full' : 'max-w-6/10';
});

defineExpose(modalApi);
</script>

<template>
  <Page>
    <VbenModal :title="isUpdate ? '编辑MSDS数据' : '新增MSDS数据'" class="w-[90%] h-auto">
      <Page content-class="flex flex-col gap-4" description="MSDS管理" header-class="p-0">
        <template #description>
          <div class="flex flex-row pb-5 px-10 gap-8">
            <Steps :current="currentCard" class="steps" @change="onChange">
              <Step title="选择组成成分" />
              <Step title="确认MSDS信息" />
            </Steps>
            <Button type="primary" @click="toggleCollapse"> {{ isCollapsed ? '展开' : '收起' }}</Button>
          </div>
        </template>
        <Card v-show="currentCard === 0">
          <div class="mx-auto max-w-2xl p-6">
            <FirstForm />
          </div>
        </Card>
        <Card v-show="currentCard === 1">
          <Tabs v-model:active-key="activeTab" :tabBarGutter="0" type="card">
            <TabPane v-for="pane in MSDSpanes" :key="pane.key" :tab="pane.title">{{ pane.content }}</TabPane> />
            <template #leftExtra>
              <Button type="primary" class="mr-5" @click="preBtn">上一项</Button>
            </template>
            <template #rightExtra>
              <Button type="primary" class="ml-5" @click="nextBtn">下一项</Button>
            </template>
          </Tabs>
          <div :class="`mx-auto ${maxWidthClass} p-6`">
            <SecondForm1 v-show="currentTab === 0" />
            <SecondForm2 v-show="currentTab === 1" />
            <SecondForm3 v-show="currentTab === 2">
              <template #compInfoSlot="slotProps">
                <compInfoGrid
                  v-bind="slotProps"
                  class="w-full"
                  table-title="成分信息"
                  table-title-help="根据所选组分生成"
                >
                  <template #cellstool="{ row }">
                    <Button type="link" @click="handleRemove(row)">
                      <!-- 20像素大小的图标 -->
                      <MdiDelete class="size-5" style="color: red" />
                    </Button>
                  </template>
                  <template #toolbar-tools>
                    <Button class="mr-2" type="primary" @click="handleAdd">新增</Button>
                    <Button class="mr-2" type="primary" danger @click="handleRemoveSelected">删除</Button>
                    <Button class="mr-2" style="background-color: #0bd092" type="primary" danger @click="handleReload"
                      >重置</Button
                    >
                    <!--Button style="background-color: #0bd092" type="primary" danger @click="ValidGrid(2)">验证</Button !-->
                  </template>
                </compInfoGrid>
              </template>
            </SecondForm3>
            <SecondForm4 v-show="currentTab === 3" />
            <SecondForm5 v-show="currentTab === 4" />
            <SecondForm6 v-show="currentTab === 5" />
            <SecondForm7 v-show="currentTab === 6" />
            <SecondForm8 v-show="currentTab === 7" />
            <SecondForm9 v-show="currentTab === 8" />
            <SecondForm10 v-show="currentTab === 9" />
            <SecondForm11 v-show="currentTab === 10" />
            <SecondForm12 v-show="currentTab === 11" />
            <SecondForm13 v-show="currentTab === 12" />
            <SecondForm14 v-show="currentTab === 13" />
            <SecondForm15 v-show="currentTab === 14" />
            <SecondForm16 v-show="currentTab === 15" />
          </div>
        </Card>
      </Page>
    </VbenModal>
  </Page>
</template>
